import request, { OptionsType } from '@/lib/request'
import { useState, useEffect, useCallback } from 'react'

const useStream = (url: string, params: any, options?: OptionsType) => {
  const [data, setData] = useState<Response | null>(null)
  const [preUrl, changePreUrl] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const fetchData = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const response = await request(url, params, options)
      if (!response.ok) {
        throw new Error(`Error: ${response.statusText}`)
      }
      setData(response)
    } catch (error: any) {
      setError(error.message)
    } finally {
      setLoading(false)
    }
  }, [url, params, options])

  useEffect(() => {
    if (url && preUrl !== url) {
      changePreUrl(url)
      fetchData()
    }
  }, [url, preUrl])

  const mutate = () => {
    fetchData()
  }

  return { data, loading, error, mutate }
}

export default useStream
